<template>
  <div>
    <Form ref="form" :model="formItem">
      <FormItem prop="authorities">
        <Transfer
          :data="selectUsers"
          :list-style="{width: '45%',height: '480px'}"
          :titles="['选择用户', '已选择用户']"
          :render-format="transferRender"
          :target-keys="formItem.userIds"
          @on-change="handleTransferChange"
          filterable>
        </Transfer>
      </FormItem>
    </Form>
  </div>
</template>

<script>

export default {
  name: 'RoleUser',
  data () {
    return {
      selectApis: [],
      selectMenus: [],
      selectUsers: [],
      formItem: this.getFormItem()
    }
  },
  methods: {
    getFormItem () {
      return {
        roleId: '',
        userIds: []
      }
    },
    setData (data) {
      if (data && data.roleId) {
        Object.assign(this.formItem, {
          roleId: data.roleId
        })
        this.handleLoadRoleUsers(data.roleId)
      }
    },
    handleReset () {
      this.$refs['form'].resetFields()
      this.formItem = this.getFormItem()
    },
    handleSubmit () {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.$http.post(this.$apis.role.saveRoleUsers, {
              roleId: this.formItem.roleId,
              userIds: this.formItem.userIds.join(',')
            }).then(res => {
              resolve(res)
            }).catch(function (err) {
              reject(err)
            })
          } else {
            resolve(false)
          }
        })
      })
    },
    handleLoadRoleUsers (roleId) {
      if (!roleId) {
        return
      }
      const that = this
      const p1 = this.$http.get(this.$apis.user.list, {}, this)
      const p2 = this.$http.get(this.$apis.role.getRoleUsers, { roleId: roleId }, this)
      Promise.all([p1, p2]).then(function (values) {
        const res1 = values[0]
        const res2 = values[1]
        if (res1.code === 0) {
          res1.data.map(item => {
            item.key = item.userId
            item.label = `${item.userName}(${item.nickName})`
          })
          that.selectUsers = res1.data
        }
        if (res2.code === 0) {
          const userIds = []
          res2.data.map(item => {
            if (!userIds.includes(item.userId)) {
              userIds.push(item.userId)
            }
          })
          that.formItem.userIds = userIds
        }
      })
    },
    transferRender (item) {
      return `<span  title="${item.label}">${item.label}</span>`
    },
    handleTransferChange (newTargetKeys, direction, moveKeys) {
      this.formItem.userIds = newTargetKeys
    },
    handleClick (name, row) {
      switch (name) {
        case 'remove':
          this.handleRemove(row)
          break
      }
    }
  },
  mounted: function () {
  }
}
</script>
